package com.lly.songhigh.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.CollectionListAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.AlbumPic;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.dao.Collection;
import com.lly.songhigh.entity.dao.CollectionDao;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 李新伟 on 15/11/7.
 */
public class MyCollectionActivity extends BaseActivity implements View.OnClickListener, CollectionListAdapter.OnRelativeClickLinstener, CollectionListAdapter.OnRelativeLongClickLinstener {

    private LinearLayout collectLinear;
    private RecyclerView collectRecycleView;
    private ImageView toolbarBack;
    private TextView linstenCount;
    private DaoSingleton daoSingleton;
    private List<Collection> collections;
    private List<Long> albumIds;
    private List<String> albumPics;
    private VolleySingleton volleySingleton;
    private CollectionListAdapter adapter;
    private ImageView chartsDetailImg;
    private TextView detailTitle;
    private CollapsingToolbarLayout detail_collapsing_toolbar;
    private List<MusicInfo> musicInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charts_detail);
        BaseApplication.getInstance().addActivity(this);
        initView();
        initData();
    }

    private void initData() {
        volleySingleton = VolleySingleton.getInstance();
        daoSingleton = DaoSingleton.getInstance();
        collections = daoSingleton.getCollection();
        SharedPreferencesUtils.putSharePre(this, "collection", "count", collections.size()); // 将数据库中的数量加入到缓存中
        albumIds = new ArrayList<>();
        albumPics = new ArrayList<>();
        for (Collection collection : collections) {
            albumIds.add(collection.getAlbumId());
        }
        for (int i = 0; i < albumIds.size(); i++) {
            StringRequestUtf stringRequestUtf = new StringRequestUtf(URL.ALBUM_PIC_START + albumIds.get(i) + URL.ALBUM_PIC_END, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    AlbumPic albumPic = gson.fromJson(response, AlbumPic.class);
                    if (albumPic.getData().getPicUrl() != null) {
                        albumPics.add(albumPic.getData().getPicUrl());
                    } else {
                        albumPics.add("");
                    }
                    if (albumPics.size() == albumIds.size()) {
                        adapter = new CollectionListAdapter(MyCollectionActivity.this, collections, albumPics);
                        collectRecycleView.setAdapter(adapter);
                        adapter.setOnRelativeClickLinstener(MyCollectionActivity.this);
                        adapter.setOnRelativeLongClickLinstener(MyCollectionActivity.this);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(stringRequestUtf);
        }
    }

    private void initView() {
        collectLinear = (LinearLayout) findViewById(R.id.collect_linear);
        collectRecycleView = (RecyclerView) findViewById(R.id.charts_detail_recycler_view);
        toolbarBack = (ImageView) findViewById(R.id.detail_toolbar_back);
        linstenCount = (TextView) findViewById(R.id.detail_listen_count);
        chartsDetailImg = (ImageView) findViewById(R.id.charts_detail_img);
        detailTitle = (TextView) findViewById(R.id.detail_title);
        detail_collapsing_toolbar = (CollapsingToolbarLayout) findViewById(R.id.detail_collapsing_toolbar);
        Picasso.with(this).load(R.mipmap.collection_background).into(chartsDetailImg);
        chartsDetailImg.setBackgroundResource(R.mipmap.collection_background);
        detailTitle.setText(StringResouce.MY_COLLECTION);
        detail_collapsing_toolbar.setTitle(StringResouce.MY_COLLECTION);
        detail_collapsing_toolbar.setExpandedTitleTextAppearance(R.style.CollapsingToolbarLayoutText);
        // 设置列表布局的方向, 通过布局管理器对象
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        collectRecycleView.setLayoutManager(layoutManager);
        collectLinear.setVisibility(View.GONE);
        linstenCount.setVisibility(View.GONE);
        toolbarBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_toolbar_back:
                finish();
                break;
        }
    }

    @Override
    public void onRelativeClick(int position, Collection collection) {
        musicInfos = new ArrayList<>();
        for (Collection collection1 : collections) {
            MusicInfo musicInfo = new MusicInfo();
            musicInfo.setUrl(collection1.getPlayUrl());
            musicInfo.setDuration(collection1.getDuration());
            musicInfo.setSingerName(collection1.getSingerName());
            musicInfo.setSongId(collection1.getSongId());
            musicInfo.setSongName(collection1.getSongName());
            musicInfo.setAlbum(collection1.getAlbum());
            musicInfo.setResouce(StringResouce.RESOUCE_NET);
            musicInfos.add(musicInfo);
        }
        Intent intent = new Intent(this, PlayMusicActivity.class);
        EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, collection.getSongName()));
        startActivity(intent);
    }

    @Override
    public void onRelativeLongClick(int position, final Collection collection) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除收藏");
        builder.setMessage("确定要删除此歌曲？");
        builder.setNegativeButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                daoSingleton.getCollectionDao().queryBuilder().where(CollectionDao.Properties.SongId
                .eq(collection.getSongId())).buildDelete().executeDeleteWithoutDetachingEntities();
                adapter.removeData(collection);
            }
        });
        builder.setPositiveButton("取消", null);
        builder.show();
    }
}
